package com.hutu.kboshi.common.exception;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;

import com.hutu.kboshi.common.BaseResponse;
import com.hutu.kboshi.common.ErrorCode;
import com.hutu.kboshi.common.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import static com.hutu.kboshi.common.ErrorCode.NOT_LOGIN_ERROR;
import static com.hutu.kboshi.common.ErrorCode.NO_AUTH_ERROR;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        log.error("BusinessException", e);
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("RuntimeException", e);
        if (e instanceof NotLoginException) {    // 如果是未登录异常
            return ResultUtils.error(NOT_LOGIN_ERROR);
        } else if (e instanceof NotRoleException ||  // 如果是角色异常
                e instanceof NotPermissionException) {  // 如果是权限异常
            return ResultUtils.error(NO_AUTH_ERROR);
        } else {
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统错误");
        }
    }
}
